/*
 * Copyright (c) 2020 Fraunhofer FOKUS and others. All rights reserved.
 *
 * See the NOTICE file(s) distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contact: mosaic@fokus.fraunhofer.de
 */
package org.eclipse.mosaic.fed.carla.clojure.commands;

import libpython_clj2.java_api;
import org.eclipse.mosaic.fed.carla.clojure.AbstractCarlaCommand;
import org.eclipse.mosaic.fed.carla.clojure.ClojureCarlaConnection;
import org.eclipse.mosaic.lib.objects.vehicle.VehicleData;

public class VehicleSynchronize extends AbstractCarlaCommand {

    public VehicleSynchronize() {
        super();
    }

    public void execute(ClojureCarlaConnection connection, VehicleData sumoVehicleData) {
        try (AutoCloseable locker = java_api.GILLocker()) {
            Object carlaTransform = getCarlaTransform(connection, sumoVehicleData);
            Object carlaLights = null;

            long carlaActorId = connection.sumo2carlaIds.get(sumoVehicleData.getName());
            Object carlaActor = getCarlaActor(connection, carlaActorId);

            if (connection.syncVehicleLights) {
                carlaLights = getCarlaLightsState(carlaActor, sumoVehicleData);
            }

            Object setTransformAttr = java_api.getAttr(carlaActor, "set_transform");
            java_api.call(setTransformAttr, carlaTransform);

            if (carlaLights != null) {
                Object setLightStateAttr = java_api.getAttr(carlaActor, "set_light_state");
                java_api.call(setLightStateAttr, carlaLights);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
